package com.gitee.huanminabc.jcommon.reflect;

import com.gitee.huanminabc.jcommon.file.IoStreamUtil;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 简要描述
 *
 * @Author: huanmin
 * @Date: 2025/4/13 15:13
 * @Version: 1.0
 * @Description: 文件作用详细描述....
 */
public class MetaInfScanner {

    //获取所有依赖的jar下的META-INF下文件
    // 注意当前项目未打包, 不会读取当前项目Resources下的META-INF下的文件 , 如果当前项目打包后就能读取到了, 这个如果需要, 就要在外边兼容
    public static List<InputStream> readFilesInMetaInf(String fileName) throws IOException {

        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        Enumeration<URL> resources = classLoader.getResources("META-INF");
        // 使用并行流加速处理
        return Collections.list(resources).parallelStream()
                .map(metaInfUrl -> findFile(metaInfUrl, fileName))
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
    }

    private static InputStream findFile(URL metaInfUrl, String fileName) {
        try {
            String filePath = getFilePath(fileName, metaInfUrl);
            //判断非jar:file开头的就是本地路径
            if (!filePath.startsWith("jar:file:")){
                File file = new File(filePath);
                if (file.exists()){
                    return IoStreamUtil.fileToInputStream(file);
                }
                return null;
            }
            return new URL(filePath).openStream(); // 找到文件时返回路径
        } catch (IOException ignored) {
            return null; // 未找到文件时返回null
        }
    }

    private static String getFilePath(String fileName, URL metaInfUrl) {
        if (metaInfUrl.getProtocol().equals("jar")) {
            String jarPath = metaInfUrl.toString()
                    .replace("jar:file:", "")
                    .replace("!/META-INF", "");
            return "jar:file:" + jarPath + "!/META-INF/" + fileName;
        } else {
            return metaInfUrl.getPath() + "/" + fileName;
        }
    }
}
